package in.co.codedoc.sql;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.sql.SQLException;
import java.util.LinkedList;

public class OrderingClause
{
	public static enum Sort
	{
		ASCENDING,
		DESCENDING;

		public Writer Generate(Writer out) 
			throws IOException
		{
			switch(this)
			{
			case ASCENDING:
				out.write("ASC");
				break;
			case DESCENDING:
				out.write("DESC");
				break;
			default:
				break;
			}
			
			return out;
		}
	}
	
	private static class Sorting
	{
		public Sorting(TableColumn column,Sort direction)
		{
			this.column = column;
			this.direction = direction;
		}
		
		public TableColumn GetColumn()
		{
			return column;
		}
		
		public Sort GetSort()
		{
			return direction;
		}
		
		private TableColumn column;
		private Sort direction;
	}

	public OrderingClause()
	{
		this(null);
	}
	
	public OrderingClause(QueryStatement owner)
	{
		this.owner = owner;
	}
	
	public void SetOwner(QueryStatement owner)
	{
		this.owner = owner;
	}
	
	public OrderingClause Ascending(TableColumn tc) 
	{
		return Sort(tc,Sort.ASCENDING);
	}
	
	public OrderingClause Descending(TableColumn tc) 
	{
		return Sort(tc,Sort.DESCENDING);
	}
	
	private OrderingClause Sort(TableColumn tc, Sort descending) 
	{
		if(owner != null)
		{
			owner.Invalidate();
		}
		
		sorts.add(new Sorting(tc,descending));
		
		return this;
	}

	public PrintWriter Generate(PrintWriter out) throws IOException
	{
		boolean firstSorting = true;
		
		for(Sorting sorting:sorts)
		{
			if(firstSorting)
			{
				out.write(" ORDER BY ");
			}
			else
			{
				out.write(',');
			}
			
			out.write(sorting.GetColumn().GetQualifiedName());
			out.write(' ');
			sorting.GetSort().Generate(out);
			
			firstSorting = false;
		}
		
		return out;
	}
	
	private QueryStatement owner;
	private LinkedList<Sorting> sorts = new LinkedList<Sorting>();
}
